package com.jeecg.demo.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.jeecgframework.core.enums.StoreUploadFilePathEnum;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.FileUtils;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.jwt.service.TokenManager;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.jwt.util.menu.ResponseMessageCodeEnum;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jeecg.demo.entity.AppFeedbackEntity;
import com.jeecg.demo.entity.AppLoginTokenEntity;
import com.jeecg.demo.entity.AppUserCollectionEntity;
import com.jeecg.demo.entity.AppVersionEntity;
import com.jeecg.demo.service.AppAboutServiceI;
import com.jeecg.demo.service.AppFeedbackServiceI;
import com.jeecg.demo.service.AppLoginTokenServiceI;
import com.jeecg.demo.service.AppUserCollectionServiceI;

/**
 * @Title: Controller
 * @Description:
 * @author onlineGenerator
 * @date 2018-08-23 14:58:22
 * @version V1.0
 * 
 */
@Api(value = "appInfo", description = "appinformation", tags = "appInfo")
@Controller
@RequestMapping("/appInfo")
public class AppInfo {
    private static final Logger logger = LoggerFactory.getLogger(AppInfo.class);
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private SystemService systemService;
    @Autowired
    private AppAboutServiceI appAboutSerive;
    @Autowired
    private AppAboutServiceI appVersionSerive;
    @Autowired
    private AppFeedbackServiceI appFeedbackSerive;
    @Autowired
    private AppUserCollectionServiceI appUserCollectSerive;
    @Autowired
    private AppLoginTokenServiceI appLoginTokenService;

    /**
     * aboutUs
     * 
     * @return
     */
    @RequestMapping(value = "/aboutUs", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "aboutUs", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> aboutUs() {

        String sql = " select * from  APP_ABOUT where about_id=? ";
        List<Map<String, Object>> listmap = systemService.findForJdbc(sql, 1);

        if (null != listmap && listmap.size() > 0) {
            return Result.success(listmap.get(0));

        }
        return null;
    }

    /**
     * helpDocument
     * 
     * @return
     */
    @RequestMapping(value = "/helpDocument", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "helpDocument", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> helpDocument() {
        String sql = " select * from  APP_ABOUT where about_id=? ";
        List<Map<String, Object>> listmap = systemService.findForJdbc(sql, 2);
        /*
         * List<AppAboutEntity> listAppAbout = appAboutSerive.
         * .getList(AppAboutEntity.class);
         */
        if (null != listmap && listmap.size() > 0) {
            return Result.success(listmap.get(0));

        }
        return null;
    }

    /**
     * get lateat app version
     * 
     * @return
     */
    @RequestMapping(value = "/appversion", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "get lateat app version", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<AppVersionEntity> appversion() {
        List<AppVersionEntity> listAppVersion = appVersionSerive
                .getList(AppVersionEntity.class);
        if (null != listAppVersion && listAppVersion.size() > 0) {
            return Result.success(listAppVersion.get(0));
        }
        return null;
    }

    /**
     * idea feedback
     * 
     * @return
     */
    @RequestMapping(value = "/addIdea", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "idea feedback", produces = "application/json", httpMethod = "POST")
    public ResponseMessage<?> addIdea(HttpServletRequest req,
            @RequestParam String content) {
        AppFeedbackEntity entity = new AppFeedbackEntity();
        entity.setFeedbackContent(content);
        entity.setCreateTime(new Date());
        try {
            appFeedbackSerive.save(entity);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error("提交失败");
        }
        return Result.success("提交成功");

    }

    /**
     * get user information
     * 
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "get user information", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> getUserInfo(@RequestParam("userid") String userid) {
        String sql = " select t.userid,t.LOGINNAME,t.mobile,t.SEX,t.username,"
                + " t.TRADERID,t.TRADERNAME,t.REGIONCODE,s.regionname as city,a.regionname as province"
                + " from V_ECP_USER t,SYS_APP_REGION s,SYS_APP_REGION a "
                + "where t.regioncode=s.regioncode and a.regioncode=s.parentcode  and t.userid=? ";
        List<Map<String, Object>> listmap = systemService.findForJdbc(sql,
                userid);
        if (null != listmap && listmap.size() > 0) {
            return Result.success(listmap.get(0));
        }
        return null;

    }

    /**
     * get user head pic
     * 
     * @return
     */
    @RequestMapping(value = "/getHeadPic", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "get user head pic", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> getHeadPic(@RequestParam("userId") String userId) {
        String sql = " select * from  APP_USER_HEADPIC where USERID=? ";
        List<Map<String, Object>> listmap = systemService.findForJdbc(sql,
                userId);
        if (null != listmap && listmap.size() > 0) {
            return Result.success(listmap.get(0));
        }
        return null;

    }

    /**
     * 更新用户头像
     * 
     * @return
     */
    @RequestMapping(value = "/uploadHeadPic", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更新用户头像", produces = "application/json", httpMethod = "POST")
    public ResponseMessage<?> uploadHeadPic(HttpServletRequest request,
            HttpServletResponse response) {
        String userId = request.getParameter("userId");
        ResponseMessage<Map<String, String>> result = null;
        Map<String, String> resultMap = new HashMap<String, String>();
        // 默认上传路径
        String ctxPath = ResourceUtil.getConfigByName("webUploadpath");
        // 文件名
        String fileName = null;
        // 上传业务名称
        // PHOTOSUCAI 照片素材
        // DEFAULT 文件
        String bizType = request.getParameter("bizType");
        // 上传路径
        String bizPath = StoreUploadFilePathEnum.getPath(bizType);
        // 上传时间
        String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());

        // 更新上传目录
        String realpath = request.getSession().getServletContext().getRealPath(
                "/")
                + "/" + ctxPath;// 文件的硬盘真实路径

        try {
            File file = new File(ctxPath + File.separator + bizPath
                    + File.separator + nowday);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }

            // 获取上传文件对象
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile mf = multipartRequest.getFile("inputName");

            // 获取文件名
            String orgName = mf.getOriginalFilename(); // 获取文件名

            String extend = FileUtils.getExtend(orgName);// 获取文件扩展名
            String noextfilename = "";// 不带扩展名
            noextfilename = DateUtils.getDataString(DateUtils.yyyymmddhhmmss)
                    + StringUtil.random(8);// 自定义文件名称
            fileName = noextfilename + "." + extend;// 自定义文件名称
            // 保存文件并写入
            String savePath = file.getPath() + File.separator + fileName;// 图片保存路径
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            LogUtil.info("======保存路径【" + savePath + "】======");

            // 设置返回结果
            String dbpath = bizPath + File.separator + nowday + File.separator
                    + fileName;

            // 根据业务要求，变更链接地址符号
            if (null != dbpath && !dbpath.equals("")) {
                if (dbpath.indexOf('\\') == 0) {
                    dbpath = dbpath.substring(1);
                }

                dbpath = dbpath.replace("\\", "/");
            }
            // 更新头像表
            // 判断该用户是否上传过头像
            String sql = " select  count(*) from  APP_USER_HEADPIC where USERID=? ";
            Long count = systemService.getCountForJdbcParam(sql, userId);
            if (count == 0) {
                String insertSql = "INSERT INTO APP_USER_HEADPIC (APP_HEADPIC_ID,SYSID,ISVAILD,HEADPIC_PATH,USERID) VALUES(?,?,?,?,?)";
                BigDecimal id = generateId("APP_HEADPIC_ID");
                systemService.executeSql(insertSql, id, id, 1, dbpath, userId);
            }
            else {
                String updateSql = "update APP_USER_HEADPIC set HEADPIC_PATH=? where USERID=?";

                systemService.executeSql(updateSql, dbpath, userId);
            }
            resultMap.put("message", "上传成功");
            resultMap.put("uploadpath", dbpath);
            result = Result.success(resultMap);
        }
        catch (IOException e) {
            result = Result.error(ResponseMessageCodeEnum.ERROR, "文件上传失败",
                    resultMap);
            logger.info(e.getMessage());
        }
        return Result.success(resultMap);

    }

    public BigDecimal generateId(String tablename) {
        BigDecimal id = null;
        String sql = "select pagnbuilder.GetNextSysID(?) as id from dual";
        List<Map<String, Object>> list = systemService.findForJdbc(sql,
                tablename);
        if (null != list && list.size() > 0) {
            Map<String, Object> map = list.get(0);
            id = (BigDecimal) map.get("id");

        }

        return id;
    }

    /**
     * 修改用户信息
     * 
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改用户信息", produces = "application/json", httpMethod = "POST")
    public ResponseMessage<?> updateUser(HttpServletRequest req,
            @RequestParam String loginname, @RequestParam String regioncode,
            @RequestParam String username, @RequestParam String unit,
            @RequestParam String userid) {
        float result = 0;
        Session session = systemService.getSession();
        try {
            CallableStatement procCall = SessionFactoryUtils.getDataSource(
                    session.getSessionFactory()).getConnection().prepareCall(
                    "{call app_userregister2(?,?,?,?,?,?)}");
            procCall.setString(1, loginname);
            procCall.setString(2, regioncode);
            procCall.setString(3, username);
            procCall.setString(4, null);
            procCall.setString(5, unit);
            procCall.setFloat(6, Float.parseFloat(userid));
            result = procCall.executeUpdate();
        }
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return Result.success(result);

    }

    /**
     * 收藏列表
     * 
     * @return
     */
    @RequestMapping(value = "/getColletList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "客户端用户列表信息", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> colletList(@RequestParam("userId") String userId) {
    	String sql = "select t.*,d.title from app_user_collection t,APP_INFORMATION d where d.info_id=t.info_id and t.current_state=1 AND t.app_user_id=?";
        List<Map<String,Object>> list = appUserCollectSerive.findForJdbc(sql,Integer.parseInt(userId));
        if (null != list && list.size() > 0) {
            return Result.success(list);
        }
        return null;
    }
    
    /**
     * 检查该信息用户是否收藏过
     * 
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/IsCollect", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "检查是否收藏", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> IsCollect(@RequestParam("infoId") String infoId,@RequestParam("userId") String userId) {
        String sql = "select count(*) from app_user_collection where app_user_id= ?  and info_id=?  and current_state=1";
        Long count = systemService.getCountForJdbcParam(sql, userId, infoId);
        return Result.success(count);
    }

    /**
     * 添加收藏
     * 
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/addCollect", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "添加收藏", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> addCollect(@RequestParam("infoid") String infoid,
            @RequestParam("userid") String userid) {
        BigDecimal id = generateId("APP_USER_COLLECTION");
        int result = 0;
        if (id != null) {
            String insertSql = "INSERT INTO app_user_collection(SYSID,INFO_ID,APP_USER_ID,CREATE_DATE,CURRENT_STATE) VALUES(?,?,?,?,?)";
            result = systemService.executeSql(insertSql, id, infoid, userid,
                    new Date(), 1);

            /*String updateSql = "update app_information set READ_COUNT=READ_COUNT+1,COLLECTION_NUM=COLLECTION_NUM+1  where  INFO_ID=?";
            result = systemService.executeSql(updateSql, infoid);*/
            return Result.success(result);
        }
        else {
            return Result.error("添加失败");
        }

    }

    /**
     * 取消收藏
     * 
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/deleteCollect", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = " 取消收藏", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> deleteCollect(
            @RequestParam("infoid") String infoid,
            @RequestParam("userid") String userid) {
        int result = 0;
        String updateSql = "update app_user_collection set CURRENT_STATE='0', cancel_date=? where  INFO_ID=?  and APP_USER_ID=? and CURRENT_STATE=1";
        result = systemService
                .executeSql(updateSql, new Date(), infoid, userid);

        /*String updateSql2 = "update app_information set READ_COUNT=READ_COUNT+1,COLLECTION_NUM=COLLECTION_NUM-1  where  INFO_ID=?";
        result = systemService.executeSql(updateSql2, infoid);*/
        return Result.success(result);
    }

    /**
     * 客户端注销用户
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "注销客户端用户", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<?> logout(@RequestParam("id") String id) {
        logger.info("logout[{}]", id);

        List<AppLoginTokenEntity> appLoginTokenList = appLoginTokenService
                .findHql("from AppLoginTokenEntity where userId=?", id);
        // 验证
        if (StringUtils.isEmpty(id)) {
            return Result.error("ID不能为空");
        }
        if (appLoginTokenList == null) {
            return Result.success("客户端用户注销成功");
        }
        try {
            appLoginTokenList.get(0).setToken(" ");
            tokenManager.deleteToken(appLoginTokenList.get(0).getLoginName());
            appLoginTokenService.saveOrUpdate(appLoginTokenList.get(0));
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("客户端用户注销失败");
        }

        return Result.success("客户端用户注销成功");
    }
}
